import docx
import os
import re

# 获取当前目录
current_dir = os.getcwd()
# 文档路径
doc_path = os.path.join(current_dir, "超市管理.docx")

# 打开文档
doc = docx.Document(doc_path)

# 创建输出文件
output_file = open("supermarket_management.cpp", "w", encoding="utf-8")

# 写入必要的头文件和预处理指令
output_file.write("""#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <conio.h>
#include <windows.h>

// 超市管理系统 - 综合版本
// 集成库存管理、销售管理、会员管理和员工管理

// 常量定义
#define LENGTH  1000 // 超市中所有商品信息数量上限
#define MAX_STAFF_COUNT 1000 // 超市中所有员工信息数量的上限
#define MAX_STOCK_COUNT 1000 // 超市中所有库存信息数量的上限
#define MAX_MEMBER_COUNT 1000 // 超市中所有会员信息数量的上限
#define MAX_SALE_COUNT 1000 // 超市中所有销售信息数量的上限

// 前向声明
int main_stock();
int sale();
int funtion();
int minmain();

""")

# 提取所有段落文本
all_text = []
for i, para in enumerate(doc.paragraphs):
    if para.text.strip():
        all_text.append(para.text.strip())

# 收集代码块，修复一些明显的问题
code_blocks = []
current_block = ""
for line in all_text:
    if not line.startswith('段落'):
        # 将行添加到当前代码块
        current_block += line + "\n"
        
        # 检查是否是代码块的结束（如函数末尾）
        if line.strip() == "}":
            if current_block.strip():
                code_blocks.append(current_block)
                current_block = ""

# 修复mainMenu函数命名冲突
fixed_code = ""
for block in code_blocks:
    # 修复mainMenu冲突
    if "void mainMenu()" in block and "销售管理系统" in block:
        block = block.replace("void mainMenu()", "void salesMainMenu()")
        block = block.replace("mainMenu();", "salesMainMenu();")
    elif "void cafeteria()" in block:
        block = block.replace("void cafeteria()", "void memberMainMenu()")
        block = block.replace("mainMenu();", "memberMainMenu();")
    elif "void printmainMenu()" in block:
        block = block.replace("void printmainMenu()", "void employeeMainMenu()")
        block = block.replace("mainMenu();", "employeeMainMenu();")
    
    fixed_code += block + "\n"

# 修复重复声明
fixed_code = fixed_code.replace("struct TrainingRecord trainings[100];", "// trainings数组声明已移到全局")
fixed_code = fixed_code.replace("struct Performance performances[100];", "// performances数组声明已移到全局")
fixed_code = fixed_code.replace("struct PerformanceInfo performances[100];", "// performances数组声明已移到全局")

# 添加函数声明以避免未定义错误
fixed_code = fixed_code.replace("do {\n        menu();", "do {\n        work();")
fixed_code = fixed_code.replace("do {\n        mainMenu();", "do {\n        employeeMainMenu();")

# 移除重复的结构体定义
fixed_code = re.sub(r'typedef struct\{\s+char empId\[20\];\s+char period\[20\];\s+int score;\s+\};Perf;', 
                    "// 重复的Perf结构体定义已移除", fixed_code)

# 修复stock_check函数
fixed_code = fixed_code.replace("4. 库存盘点（统计总库存价值）", "void stock_check() {")

# 写入修复后的代码
output_file.write(fixed_code)

# 关闭文件
output_file.close()

print(f"优化后的超市管理系统代码已成功生成到 {os.path.join(current_dir, 'supermarket_management.cpp')}")
print("请在Dev-C++中打开并编译运行该文件。") 